package cn.smile.business.notebook.impl;

import cn.smile.bean.entity.notebook.NotebookImage;
import cn.smile.business.notebook.INotebookImageService;
import cn.smile.commons.domain.BaseServiceImpl;
import cn.smile.repository.notebook.NotebookImageMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class NotebookImageServiceImpl extends BaseServiceImpl<NotebookImageMapper, NotebookImage> implements INotebookImageService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveImageList(List<String> imageList, String notebookId) {
        log.info("[NotebookImageServiceImpl].[saveImageList] ------> 保存日记附件图片集合 Start");
        //删除之前的
        List<NotebookImage> oldList = baseMapper.selectList(new QueryWrapper<NotebookImage>().lambda().eq(NotebookImage::getNotebookId, notebookId).eq(NotebookImage::getDeleted, Boolean.FALSE));
        if (!CollectionUtils.isEmpty(oldList)) {
            oldList.forEach(image -> super.delById(image.getId()));
        }
        if (!CollectionUtils.isEmpty(imageList)) {
            for (String imageUrl : imageList) {
                NotebookImage entity = new NotebookImage();
                entity.setNotebookId(notebookId);
                entity.setFileUrl(imageUrl);
                super.create(entity);
            }
        }
        log.info("[NotebookImageServiceImpl].[saveImageList] ------> 保存日记附件图片集合 End");
    }

    @Override
    public Map<String, List<String>> getImageMap(List<String> notebookIds) {
        log.info("[NotebookImageServiceImpl].[getImageMap] ------> 根据日记记录ID查询图片附件集合 Start");
        Map<String, List<String>> imageMap = Maps.newHashMap();
        List<NotebookImage> imageList = baseMapper.selectList(new QueryWrapper<NotebookImage>().lambda().eq(NotebookImage::getDeleted, Boolean.FALSE).in(NotebookImage::getNotebookId, notebookIds));
        if (!CollectionUtils.isEmpty(imageList)) {
            for (NotebookImage image : imageList) {
                if (!imageMap.containsKey(image.getNotebookId())) {
                    imageMap.put(image.getNotebookId(), Lists.newArrayList());
                }
                imageMap.get(image.getNotebookId()).add(image.getFileUrl());
            }
        }
        log.info("[NotebookImageServiceImpl].[getImageMap] ------> 根据日记记录ID查询图片附件集合 End");
        return imageMap;
    }
}
